import { NextRequest, NextResponse } from 'next/server';
import { mockUsers } from '@/mock/users';
import { User, UpdateUserRequest, ApiResponse } from '@/types/user';

// 模拟数据存储（与 /api/users 共享）
let users: User[] = [...mockUsers];

// GET /api/users/[id] - 获取单个用户详情
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const user = users.find(u => u.id === id);

    if (!user) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    const response: ApiResponse<User> = {
      success: true,
      data: user,
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取用户详情失败:', error);
    return NextResponse.json(
      { success: false, message: '获取用户详情失败' },
      { status: 500 }
    );
  }
}

// PUT /api/users/[id] - 更新用户
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const body: UpdateUserRequest = await request.json();

    const userIndex = users.findIndex(u => u.id === id);
    if (userIndex === -1) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户名和邮箱是否已被其他用户使用
    if (body.username || body.email) {
      const existingUser = users.find(u => 
        u.id !== id && (
          (body.username && u.username === body.username) ||
          (body.email && u.email === body.email)
        )
      );
      if (existingUser) {
        return NextResponse.json(
          { success: false, message: '用户名或邮箱已被其他用户使用' },
          { status: 400 }
        );
      }
    }

    // 更新用户
    const updatedUser: User = {
      ...users[userIndex],
      ...body,
      updatedAt: new Date().toISOString(),
    };

    users[userIndex] = updatedUser;

    const response: ApiResponse<User> = {
      success: true,
      data: updatedUser,
      message: '用户更新成功',
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('更新用户失败:', error);
    return NextResponse.json(
      { success: false, message: '更新用户失败' },
      { status: 500 }
    );
  }
}

// DELETE /api/users/[id] - 删除用户
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;

    const userIndex = users.findIndex(u => u.id === id);
    if (userIndex === -1) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查是否为管理员用户
    if (users[userIndex].role === 'admin') {
      return NextResponse.json(
        { success: false, message: '不能删除管理员用户' },
        { status: 403 }
      );
    }

    // 删除用户
    users.splice(userIndex, 1);

    const response: ApiResponse<null> = {
      success: true,
      data: null,
      message: '用户删除成功',
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('删除用户失败:', error);
    return NextResponse.json(
      { success: false, message: '删除用户失败' },
      { status: 500 }
    );
  }
} 